﻿using Autofac;
using AutoMapper;
using leapt.Api;
using leapt.Api.Middleware;
using leapt.AutoMapperConfig;
using leapt.Repositories;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.IdentityModel.Tokens;
using NLog.Extensions.Logging;
using NLog.Web;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Claims;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
using System.Threading.Tasks;
using IdentityModel;
using leapt.Api.Filter;
using IdentityServer4.AccessTokenValidation;
using Microsoft.Extensions.Options;
using leapt.Common.Tools;

namespace leapt.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        /// <summary>
        /// 这个方法被运行时调用。 使用此方法将服务添加到容器。
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            //添加options
            services.AddOptions();
            //读取配置
            services.Configure<WebApiOption>(Configuration.GetSection("WebAPI"));
            IServiceProvider serviceProvider = services.BuildServiceProvider();
            //获取配置
            WebApiOption config = serviceProvider.GetService<IOptions<WebApiOption>>().Value;

            #region 授权认证

            //使用IdentityServer授权认证
            services.AddAuthentication(o => {
                o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                o.Authority = config.Auth.AuthorityUrl;   
                o.Audience = "leapt_auth_api";
                o.RequireHttpsMetadata = false;
                //支持uri传递token
                o.Events = new JwtBearerEvents()
                {
                    OnMessageReceived = context =>
                    {
                        context.Token = context.Request.Query["access_token"];
                        return Task.CompletedTask;
                    },
                    //OnTokenValidated 在Token验证通过后调用
                    //OnAuthenticationFailed = context =>
                    //{
                    //    context.Response.StatusCode = 500;
                    //    context.Response.ContentType = "text/plain";
                    //    if (Environment.IsDevelopment())
                    //    {
                    //        return context.Response.WriteAsync(context.Exception.ToString());
                    //    }
                    //    return context.Response.WriteAsync("An error occurred processing your authentication.");
                    //}

                    //OnChallenge  //未授权时调用。
                };
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = JwtClaimTypes.Name,
                    RoleClaimType = JwtClaimTypes.Role,
                };
            });

            #endregion

            #region AutoMapper
            services.AddAutoMapper(am =>
            {
                new AutoMapperStartupTask().Execute();
            });
            #endregion

            services.AddMvc().AddMvcOptions(options=> {
                options.Filters.Add(typeof(WebApiResultMiddleware));
                options.RespectBrowserAcceptHeader = true;
            });

            #region Swagger ui

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "HFelix接口文档",
                    Description = "HFelix RESTful API 接口说明",
                    TermsOfService = "None",
                    Contact = new Swashbuckle.AspNetCore.Swagger.Contact
                    {
                        Name = "felixhpp",
                        Email = "felixhpp@163.com"
                    },
                });
                
                c.OperationFilter<AddAuthTokenHeaderParameter>(); 
                // Set the comments path for the Swagger JSON and UI.
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath = Path.Combine(basePath, "demoapi.xml");
                c.IncludeXmlComments(xmlPath);
            });

            #endregion

            #region 添加cors服务

            services.AddCors(options => options.AddPolicy(WebApiOption.CORS_POLICY_NAME, 
                p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));

            #endregion
            
            #region 获取数据库配置信息
            
            DbFactory.DB_ConnectionString = config.DB.ConnectionString;

            #endregion
           
        }

    /// <summary>
    /// 改方法中直接使用Autofac注册的地方
    /// 这会在ConfigureServices之后运行
    /// </summary>
    /// <param name="builder"></param>
    public void ConfigureContainer(ContainerBuilder builder)
        {
            //将服务添加到Autofac ContainerBuilder。
            builder.RegisterModule(new AutofacModule());
        }

        /// <summary>
        /// 这个方法被运行时调用。 使用此方法配置HTTP请求管道。
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="loggerFactory"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            #region NLog日志

            loggerFactory.AddNLog();
            app.AddNLogWeb();
            loggerFactory.ConfigureNLog("nlog.config");

            #endregion

            #region 解决Ubuntu Nginx 代理不能获取IP问题

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            #endregion

            #region Swagger
            app.UseStaticFiles();
            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger(c=> 
            {
                c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Host = httpReq.Host.Value);
                c.RouteTemplate = "swagger/{documentName}/swagger.json";
            });
            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });
            #endregion
            
            
            app.UseStatusCodePages();
            app.UseAuthentication();
            ////添加权限中间件, 一定要放在app.UseAuthentication后
            app.UsePermission(new PermissionMiddlewareOption()
            {
                //这个集合从数据库中查出所有用户的全部权限
                UserPerssions = new List<UserPermission>()
                 {
                     new UserPermission { Url="/", UserName="test1"},
                     new UserPermission { Url="/api/user/info", UserName="test"},
                     new UserPermission { Url="/home/about", UserName="aaa"},
                     new UserPermission { Url="/", UserName="aaa"}
                 }
            });

            #region 异常处理
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler();

            }
            app.UseErrorHandling();
            #endregion

            app.UseMvc();
        }
    }
}
